package blyth;

import java.awt.Point;

public class CheckTask extends Task {
    
    public CheckTask(World world, Point goal) {
        super(world, 4, goal);
    }

    @Override
    public boolean IsValid() {
        if (World.turnsSinceLastFoodAction < World.foodlessTurnLimit || assignedTo.isBlocked) {
            return false;
        }
        return World.turn - world.tile[goal.x][goal.y].lastCheck >= 10;
    }

    @Override
    public int AvailabilityFrom(Agent agent) {
        // Agent is blocked
        if (agent.isBlocked || agent.goalBlocked) {
            return Distance(agent) + 1000;
        }
        if (WontMakeItToGoal(agent)) {
            return Distance(agent) + 120;
        }
        return Distance(agent);
    }

    @Override
    public Command Solve() {
        return world.Approach(assignedTo, goal);
    }

    public static CheckTask MakeNew(World world) {
        if (World.turnsSinceLastFoodAction > World.foodlessTurnLimit) {
            boolean isThereCheckTask = false;
            for (int i = 0; i < world.Friendlies.size(); i++) {
                for (int j = 0; j < world.Friendlies.get(i).tasks.size(); j++) {
                    if (world.Friendlies.get(i).tasks.get(j).priority == 4) {
                        isThereCheckTask = true;
                    }
                }
            }
            if (isThereCheckTask == false) {
                // Search for a check task
                int oldestCheck = -1, largestEdgeHassle = 0, currentCheck, currentEdgeHassle;
                Point p = new Point();
                for (int x = 0; x < World.worldWidth; x++) {
                    for (int y = 0; y < World.worldHeigth; y++) {
                        currentCheck = World.turn - world.tile[x][y].lastCheck;
                        currentEdgeHassle = World.CalculateEdgeHassle(x, y);
                        if (oldestCheck == -1 || oldestCheck < currentCheck ||
                                (oldestCheck == currentCheck && currentEdgeHassle > largestEdgeHassle)) {
                            p.setLocation(x,y);
                            oldestCheck = currentCheck;
                            largestEdgeHassle = currentEdgeHassle;                            
                        }
                    }
                }
                return new CheckTask(world, p);
            }
        }
        return null;
    }
}
